package com.example.demo.controller;

import com.example.demo.utils.CommonRetumType;
import com.example.demo.utils.error.BusinessException;
import com.example.demo.utils.error.EmBusinessError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class BaseController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

//    异常接管类
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(HttpServletRequest request, Exception ex)
    {
        Map<String,Object> respomseData = new HashMap<>();
        if(ex instanceof BusinessException)
        {
            BusinessException businessException = (BusinessException)ex;
            respomseData.put("errCode",businessException.getErrcode());
            respomseData.put("errMsg",businessException.getErrMsg());
            return CommonRetumType.create(respomseData,"fail");
        }else {
            respomseData.put("errCode", EmBusinessError.UNKNOWN_ERROR.getErrcode());
            respomseData.put("errMsg",EmBusinessError.UNKNOWN_ERROR.getErrMsg());
            return CommonRetumType.create(respomseData,"fail");
        }
    }



    /**
     * 普通缓存获取
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     * @param key 键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            //e.printStackTrace();
            return false;
        }
    }
}
